package zl.Untils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static SessionFactory factory;
	static {
		factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
	}
	
	private static ThreadLocal<Session> session = new ThreadLocal<>();
	

	public static Session openSession() {
		Session s = session.get();
		if(s==null || !s.isOpen()) {
			s = factory.openSession();
			session.set(s);
		}
		return s;
	}
	

	public static void closeSession() {
		Session s = session.get();
		session.set(null);
		
		if(s!=null && s.isOpen()) {
			s.close();
		}
	}
	

	public static void destory() {
		if(factory.isOpen()) {
			factory.close();
		}
	}
}
